package org.test;

import java.io.BufferedReader;


import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

/*When the user logs in its all details from the remote database are rendered using this
 * class. By all details I mean all the books that are uploaded by this user
 * are listed using this class plus user is given a option to delete 
 * those books that are sold already
 * */

public class LogedInUserDetailsPageActivity extends ListActivity {
	private String ID;
	private String BookDetails[] = new String[20];

	private int counter = 0;
	private String idGot;
	ArrayList<String> stringList = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		String result = "";

		super.onCreate(savedInstanceState);
		

		Bundle extras = getIntent().getExtras();

		if (extras == null) {
			return;
		}
		ID = (String) extras.getSerializable("ID");

		System.out.println("ID we got: " + ID);

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("ID", ID));

		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(
				"http://hci.cs.sfsu.edu/~fall2010.03/Includes/GetAllBooksOfStudent.php");
		try {
			httppost.setEntity(new UrlEncodedFormEntity(postParameters));

			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();

			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();

			result = sb.toString();
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		try {
			JSONArray jArray = new JSONArray(result);

			for (int i = 0; i < jArray.length(); i++) {
				JSONObject json_data = jArray.getJSONObject(i);
				Log.i("log_tag", " Title: " + json_data.getString("Title")
						+ ", Author: " + json_data.getString("Author")
						+ ", Price: " + json_data.getString("Book_Price")
						+ ", ID: " + json_data.getString("Id"));

				BookDetails[counter] = "Title: " + json_data.getString("Title")
						+ "\nAuthor: " + json_data.getString("Author")
						+ "\nPrice: " + json_data.getString("Book_Price")
						+ "\nRecord Numer: " + json_data.getString("Id");
				
				stringList.add(BookDetails[counter]);
				counter++;

			}

		} catch (JSONException e) { 
			System.out.println("NO RECORDS FOUND");
			System.out.println("Error got: " + e.getMessage());
		}

		setListAdapter(new ArrayAdapter<String>(this, R.layout.test, stringList));
		
		ListView listView = getListView();

		listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				String text = ((TextView) view).getText().toString();
				idGot = text.substring(text.length() - 2, text.length());
				System.out.println("ID is : " + idGot);

				AlertDialog alertDialog = new AlertDialog.Builder(
						LogedInUserDetailsPageActivity.this).create();
				alertDialog.setTitle("Book Sold");
				alertDialog.setMessage("Sure you want to delete?");

				alertDialog.setButton2("No Dont Delete",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
							}
						});

				alertDialog.setButton("Yes Delete",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {

								@SuppressWarnings("unused")
								String result = null;
								ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
								postParameters.add(new BasicNameValuePair(
										"Delete", idGot));

								HttpClient httpclient = new DefaultHttpClient();
								HttpPost httppost = new HttpPost(
										"http://hci.cs.sfsu.edu/~fall2010.03/Includes/DeleteBook.php");
								try {
									httppost
											.setEntity(new UrlEncodedFormEntity(
													postParameters));

									HttpResponse response = httpclient
											.execute(httppost);
									HttpEntity entity = response.getEntity();
									InputStream is = entity.getContent();

									// convert response to s
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									StringBuilder sb = new StringBuilder();
									String line = null;
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();

									result = sb.toString();
								} catch (Exception e) {
									Log.e("log_tag", "Error converting result "
											+ e.toString());
								}

								Intent i1 = new Intent(
										LogedInUserDetailsPageActivity.this,
										UserLogedInPageActivity.class);
								i1.putExtra("ID", ID);
								startActivity(i1);

							}
						});

				alertDialog.show();

			}

		});

		System.out.println("*****************");
		for (int i = 0; i < counter; i++)
			System.out.println("Details: " + BookDetails[i]);

		System.out.println("Contents of al: " + stringList);
		
	}
	
	
	//THE LOGOUT FUNCTIONALITY
	public void logout(View view) throws Exception {

		Intent i = new Intent(this, NewOrExisitingUserActivity.class);

		startActivity(i);

	}

}